<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">登录</h2>
      <form @submit.prevent="handleLogin">
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        <input
            type="text"
            v-model="form.username"
            placeholder="请输入用户名"
            class="login-input"
            :disabled="loading"
        />
        <input
            type="password"
            v-model="form.password"
            placeholder="请输入密码"
            class="login-input"
            :disabled="loading"
        />

        <div class="login-options">
          <label>
            <input
                type="checkbox"
                v-model="form.rememberMe"
                :disabled="loading"
            />
            下次自动登录
          </label>
          <RouterLink to="/forgot_password" class="forget-password">忘记密码</RouterLink>
        </div>

        <button
            type="submit"
            class="login-button"
            :disabled="loading"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
      <div class="register-option">
        还没有账号？
        <RouterLink to="/register" class="register-link">马上注册</RouterLink>
      </div>

          <SocialLogin :loading="loading" />

    </div>
  </div>
</template>

<script setup>
import {useUserStore} from '@stores/userStore.js'
import SocialLogin from '@/components/accounts/auth/SocialLogin.vue'

const router = useRouter()
const userStore = useUserStore()

const form = reactive({
  username: '',
  password: '',
  rememberMe: false
})

const loading = ref(false)
const errorMessage = ref('')

onMounted(() => {
  // 自动填充记住的账号
  const rememberedUser = localStorage.getItem('rememberedUser')
  if (rememberedUser) {
    form.username = rememberedUser
    form.rememberMe = true
  }
})
// 表单验证抽离
const formValidation = () => {
  if (!form.username.trim() || !form.password) {
    errorMessage.value = "用户名或密码不能为空"
    return false
  }
  return true
}
// 错误处理抽离
const handleError = (error) => {
  console.error('登录失败:', error);
  // 检查是否有网络连接
  if (!navigator.onLine) {
    errorMessage.value = "当前无网络连接，请检查网络后重试";
    return;
  }

  // 根据错误类型设置不同的提示信息
  const defaultMsg = "登录失败，请检查凭证是否正确";
  const errorResponse = error.response?.data;
  switch (error.code) {
    case 'ECONNABORTED':
      errorMessage.value = "请求超时，请检查网络连接";
      break;
    case 'ERR_NETWORK':
      errorMessage.value = "网络请求失败，请稍后重试";
      break;
    default:
      errorMessage.value = errorResponse?.message || defaultMsg;
      // 如果错误代码是400, 可能是用户名或密码错误
      if (error.response?.status === 400) {
        errorMessage.value = "用户名或密码错误";
      }
      // 如果错误代码是500, 可能是服务器内部错误
      else if (error.response?.status === 500) {
        errorMessage.value = "服务器错误，请稍后重试";
      }
      break;
  }
}

const handleLogin = async () => {
  // 表单验证
  if (!formValidation()) return

  loading.value = true
  errorMessage.value = ""

  try {
    const {data} = await axios.post('/api/accounts/login/', {
      username: form.username,
      password: form.password
    })

    // 处理记住我功能
    if (form.rememberMe) {
      localStorage.setItem('rememberedUser', form.username)
    } else {
      localStorage.removeItem('rememberedUser')
    }

    // 保存用户信息到Pinia
    userStore.setAuthInfo(data.access, data.username)

    // 跳转到首页或来源页面
     // 读取来源页面并跳转
    const referrer = sessionStorage.getItem('referrer');
    if (referrer) {
      await router.push(referrer);
    } else {
      await router.push('/');
    }
    sessionStorage.removeItem('referrer');
  } catch (error) {
    handleError(error)
  } finally {
    loading.value = false
  }
}

</script>

<style scoped>

/* 整体布局 */
.login-container {
  background-image: url('@/assets/accounts/img/login_bg.jpg');
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-size: cover;
  background-position: center;
  background-color: #f5f7fa;
  background-attachment: fixed;
  position: relative;
}

.login-container::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  z-index: 1;
}

.login-box {
  width: 360px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  z-index: 2;
}

/* 登录标题 */
.login-title {
  color: #f37530;
  font-size: 1.8rem;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
  text-align: center;
}

/* 输入框样式 */
.login-input {
  width: 100%;
  height: 40px;
  margin-bottom: 20px;
  padding: 0 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 1rem;
  box-sizing: border-box;
}

/* 登录选项 */
.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-options label {
  font-size: 0.9rem;
  color: #666;
}

.forget-password {
  font-size: 0.9rem;
  color: #00aaff;
  text-decoration: none;
}

.forget-password:hover {
  color: #ff5722;
}

/* 按钮样式 */
.login-button {
  background: #FF7F50;
  color: #fff;
  border: none;
  width: 100%;
  height: 40px;
  font-size: 1rem;
  border-radius: 5px;
  cursor: pointer;
}

.login-button:hover {
  background: #ff5722;
}

/* 注册选项 */
.register-option {
  margin-top: 10px;
  font-size: 0.9rem;
  color: #666;
}


.register-link {
  color: #00aaff;
  text-decoration: none;
}

.register-link:hover {
  color: #ff5722;
}

/* 其他登录方式 */
.other-login {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.other-login-title {
  font-size: 14px;
  color: #999;
}


/* 新增错误提示样式 */
.error-message {
  color: #ff4444;
  margin-bottom: 15px;
  font-size: 0.9rem;
  text-align: left;
  padding: 8px;
  background: #ffeeee;
  border-radius: 4px;
}

/* 修改按钮禁用样式 */
.login-button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

@media (max-width: 992px) {
  .login-container {
    padding: 30px;
    height: calc(100vh + 30px);
  }
}


</style>
